import path from 'path'
import autoprefixer from 'autoprefixer'
import postcssModulesValues from 'postcss-modules-values'
import postcssModules from 'postcss-modules'
import crypto from 'crypto'

import type { UserConfig } from 'vite'

const projectName: string = 'front-frame'
export const ENVPREFIX = ['NODE_', 'VITE_']

/** @type {import('vite').UserConfig} */
export default {
  // share Options:https://vite.dev/config/shared-options.html
  mode: process.env.NODE_ENV === 'production' ? 'production' : 'development',
  root: process.cwd(),
  base: '/',
  cacheDir: 'node_modules/.vite',
  resolve: {
    alias: [{ find: '@', replacement: path.resolve(process.cwd(), 'src') }],
    extensions: ['.mjs', '.js', '.mts', '.ts'],
  },
  css: {
    // @ts-ignore
    modules: {
      generateScopedName: (name: string, filename: string): string => {
        // console.warn('name', name)
        // console.warn('filename', filename)
        // console.warn('css', css)
        var file = path.basename(filename, '.css').replace('.', '-').replace(/\?.*$/, '')
        const hash = crypto
          .createHash('md5')
          .update(filename + name)
          .digest('hex')
          .slice(0, 8)
        return process.env.NODE_ENV === 'development'
          ? file + '_' + name + '_' + hash
          : name + '_' + hash
      },
    },
    postcss: {
      plugins: [
        autoprefixer({
          cascade: false,
        }),
        postcssModulesValues(),
        postcssModules({
          /**
           * a JSON file with exported classes will be placed next to corresponding CSS
           * you have a freedom to make everything you want with exported classes, just use the getJSON callback
           */
          // @ts-ignore
          getJSON: function (_cssFileName: any, _json: any, _outputFileName: string) {
            /**
            * This is the write method for saving files.
            *
            // console.log('outputFileName', _outputFileName)
            // console.log('_cssFileName', _cssFileName)
            // console.log('_json', _json)
            const cleanName = _cssFileName.split('?')[0] // 去掉 query 参数
            if (!cleanName.endsWith('.module.css')) return
            const cssName = path.basename(cleanName, '.css')
            const buildDir = path.resolve('./.css.build/')
            const jsonFileName = path.resolve('./.css.build/' + cssName + '._json')
            if (!fs.existsSync(buildDir)) {
              fs.mkdirSync(buildDir, { recursive: true })
            }
            fs.writeFileSync(jsonFileName, JSON.stringify(_json))
            *
            */
          },
          scopeBehaviour: 'local',
          generateScopedName: function (name: string | any) {
            return name
          },
          hashPrefix: `${projectName}`,
          localsConvention: 'camelCaseOnly',
          exportGlobals: true,
          resolve: function (file: string, importer: string) {
            return path.resolve(path.dirname(importer), file.replace(/^@/, process.cwd() + '/src'))
          },
        }),
      ],
    },
    preprocessorOptions: {
      scss: {
        api: 'modern-compiler',
      },
    },
    preprocessorMaxWorkers: true,
  },
  json: {
    namedExports: true,
    stringify: true,
  },
  envPrefix: ENVPREFIX,
  appType: 'spa',
  // Server Options:https://vite.dev/config/server-options.html
  server: {
    host: '0.0.0.0',
    port: 8080,
  },
} satisfies UserConfig
